﻿Public Class clsWebWithCookies
    'Создаем объект веб запросов
    Public oHttpXML As New MSXML2.XMLHTTP60
    Public Status As Long
    Public charset As String = "windows-1251" '"utf-8"
    Public keep_alive As Integer = 300
    Public browser As String = "Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.16"


    'Отправка POST запроса по адресу sURL
    'и возврат ответа от сервера
    Public Function UploadString(ByVal sURL As String, ByVal PostData As String, Optional ByVal cookie As Boolean = False) As String
        'Dim POST() As Byte
        'PostData = StrConv(PostData, vbUnicode)
        'POST = StrConv(PostData, vbUnicode)
        Try
            With oHttpXML
                .open("POST", sURL, False)
                .setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
                SetHeaders(cookie)
                .send(PostData)
                Status = .status
                If .status <> 200 Then
                    Return ""
                Else
                    Return .responseText
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message)
            Status = 0
            Return ""
        End Try
    End Function



    Public Function DownloadString(ByVal sURL As String, Optional ByVal cookies As Boolean = False) As String
        Try
            With oHttpXML
                .open("GET", sURL, False)
                SetHeaders(cookies)
                .send()
                Status = .status
                If .status <> 200 Then
                    Return ""
                Else
                    'DownloadString = StrConv(.responsetext, vbFromUnicode)
                    Return .responseText
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message)
            Status = 0
            Return ""
        End Try
    End Function


    Private Sub SetHeaders(ByVal cookie As Boolean)
        With oHttpXML
            .setRequestHeader("If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 UTC") 'чтобы избежать кеширования
            If browser <> "" Then
                .setRequestHeader("User-Agent", browser)
            End If
            If charset <> "" Then
                .setRequestHeader("Accept-Charset", charset)
            End If
            If keep_alive <> 0 Then
                .setRequestHeader("Keep-Alive", keep_alive)
                .setRequestHeader("Connection", "keep-alive")
            End If
            If cookie = True Then
                .setRequestHeader("Cookie", "")
            End If
            'если вы сидите за proxy раскомментируйте следующие строки и подставьте верные IP, логин и пароль
            '.setProxy 2, "192.168.100.1:3128"
            '.setProxyCredentials "user", "password"
        End With
    End Sub

End Class
